package offerv1;

import leetcodev1.链表.Solution;

public class Offer22 {
    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode virtualNode = new ListNode(-1), quick = virtualNode, slow = virtualNode;
        virtualNode.next = head;
        while (quick != null && k > 0) {
            quick = quick.next;
            k--;
        }

        if (k != 0) {
            throw new RuntimeException();
        }

        while (quick != null) {
            quick = quick.next;
            slow = slow.next;
        }

        return slow;
    }
}

class Answer20 {
    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode fast = head;
        ListNode slow = head;

        while (fast != null && k > 0) {
            fast = fast.next;
            k--;
        }
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }

        return slow;
    }
}
